package com.neusoft.mid.msf.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @program: pangu
 * @description: Bean工具类, 方便用户通过非注入的方式, 获取bean对象
 * @author: fengjd
 * @create: 2022-07-21 20:41
 **/
public class BeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public  void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanUtil.applicationContext = applicationContext;
    }

    public static Object getBean(String beanName) throws BeansException {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(String name ,Class<T> requiredType ) throws BeansException {
        if (applicationContext==null) {
            return null;
        }
        return applicationContext.getBean(name,requiredType);
    }

    public static Object getBean(String name , Object... args) throws BeansException {
        if (applicationContext==null) {
            return null;
        }
        return applicationContext.getBean(name,args);
    }

    public static <T> T getBean(Class<T> requiredType ,Object... args) throws BeansException {
        if (applicationContext==null) {
            return null;
        }
        return applicationContext.getBean(requiredType,args);
    }


}
